<template>
  <div>
    <wk-page-header
      :title="config.showModuleName ? $t('crm.product.a9326e709cc0257869df07d96316a738') : ''"
      :help="getHelpObj(crmType, 'index')"
      :dropdowns="getDefaultHeaderHandes()"
      @command="pageHeaderCommand">
      <template slot="right">
        <el-button v-if="saveAuth" type="primary" @click="createClick">
          {{ $t('crm.product.7db460ff0c8b2127cf5914f1afaa5ed4') }}
        </el-button>
      </template>
    </wk-page-header>

    <div
      v-empty="!indexAuth"
      xs-empty-icon="nopermission"
      :xs-empty-text="$t('crm.product.792efe337742c53b10592a2a4dd5bbd0')"
      class="crm-container">
      <wk-table-header
        :search.sync="search"
        :tabs="sceneList"
        :active-tab.sync="sceneId"
        :selection-list="tableSelectionList"
        :operations="handleOperations"
        :condition-type-fun="conditionTypeFun"
        :fields="getFilterFields"
        :props="tableHeaderProps.props"
        :filter-header-props="tableHeaderProps.filterHeaderProps"
        :filter-form-props="tableHeaderProps.filterFormProps"
        :scene-set-props="tableHeaderProps.sceneSetProps"
        :scene-create-props="tableHeaderProps.sceneCreateProps"
        @tabs-change="sceneSelect"
        @operations-click="tableOperationsClick"
        @event-change="tableHeaderHandle"
        @filter-change="handleFilter"
      >
        <template v-if="tableStyleObj.viewType === '2'" slot="custom">
          <el-select
            v-model="activeFlow"
            value-key="flowId"
            class="flow-wrapper">
            <el-option
              v-for="flow in flowList"
              :key="flow.flowId"
              :label="flow.flowName"
              :value="flow" />
          </el-select>
        </template>

        <wk-toggle-button
          v-if="activeFlow"
          v-model="tableStyleObj.viewType">
          <wk-toggle-item value="1">
            <i class="wk wk-icon-three-line" />
          </wk-toggle-item>
          <wk-toggle-item value="2">
            <i class="wk wk-icon-org-solid" />
          </wk-toggle-item>
        </wk-toggle-button>
      </wk-table-header>

      <stage-view
        v-if="tableStyleObj.viewType === '2' && activeFlow"
        :key="`${activeFlow.flowId}${refreshKey}`"
        :base-params="baseParams"
        :flow-item="activeFlow"
        @enter-detail="enterDetail" />

      <template v-else>
        <el-table
          id="crm-table"
          v-loading="loading"
          :row-height="rowHeight"
          :data="list"
          :height="tableHeight"
          :cell-class-name="cellClassName"
          :row-key="`${crmType}Id`"
          :class="crmTableClass"
          :stripe="tableStyleObj.stripe"
          use-virtual
          highlight-current-row
          style="width: 100%;"
          @row-click="handleRowClick"
          @sort-change="sortChange"
          @header-dragend="handleHeaderDragend"
          @selection-change="handleSelectionChange">
          <el-table-column
            show-overflow-tooltip
            reserve-selection
            type="selection"
            fixed
            align="center"
            width="55" />
          <el-table-column
            fixed
            width="60">
            <template
              slot="header"
              slot-scope="{}">
              <i class="el-icon-star-off focus-icon is-disabled" />
            </template>
            <template slot-scope="scope">
              <el-tooltip :content="scope.row.star == 0 ? '添加关注' : '取消关注'" effect="dark" placement="top">
                <i
                  v-if="scope.row.star == 0"
                  class="el-icon-star-off focus-icon"
                  @click="toggleStar(scope.row)" />
                <i
                  v-else
                  class="wk wk-focus-on focus-icon active"
                  @click="toggleStar(scope.row)" />
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column
            v-for="(item, index) in fieldList"
            :key="index"
            :fixed="item.isLock === 1"
            :prop="item.prop"
            :label="item.label"
            :width="item.width"
            :class-name="item.width>60 ? 'column' : '' "
            sortable="custom"
            show-overflow-tooltip>
            <template v-if="item.width>60" slot="otherHeader" slot-scope="{}">
              <el-button
                :icon="item.isLock === 1 ? 'wk wk-unlock' : 'wk wk-lock'"
                class="el-lock-btn"
                type="text"
                @click.stop="fieldFixed(item)" />
              <el-button
                v-if="showFilter(item)"
                class="el-filter-btn"
                type="text"
                icon="wk wk-screening"
                @click.stop="showFilterClick(item)" />
            </template>
            <template slot-scope="{ row, column }">
              <!-- 产品主图 -->
              <img-view
                v-if="column.property==='mainFile'"
                :src="row[column.property]" />
              <wk-field-view
                v-else
                :props="item"
                :ignore-fields="['status']"
                :form-type="item.formType"
                :value="row[column.property]"
              >
                <template slot-scope="{ data }">
                  <span v-if="data.props.fieldName === 'status'">
                    <i v-if="getStatusIcon(row[column.property])" :style="getStatusIcon(row[column.property]).style" :class="getStatusIcon(row[column.property]).icon" />{{ row[column.property] }}
                  </span>
                  <span v-else>{{ fieldFormatter(row, column, row[column.property], item) }}</span>
                </template>
              </wk-field-view>
            </template>
          </el-table-column>
          <el-table-column />

          <wk-empty
            slot="empty"
            :props="{
              buttonTitle: $t('crm.product.1f0d3d4ade200e8e23c091792d981008'),
              showButton: saveAuth
            }"
            @click="createClick"
          />
          <field-set
            slot="other"
            :crm-type="crmType"
            @change="setSave" />
        </el-table>
        <div class="p-contianer">
          <el-dropdown trigger="click" placement="top">
            <el-button class="dropdown-btn"><i class="el-icon-s-fold" /></el-button>
            <el-dropdown-menu slot="dropdown" class="wk-table-style-dropdown-menu">
              <el-dropdown-item>
                <span @click.stop>
                  <el-switch v-model="tableStyleObj.rightBorderShow" />
                  {{ $t('crm.product.055401b202aecfc0b13e00fda736e5cd') }}
                </span>
              </el-dropdown-item>
              <el-dropdown-item>
                <span @click.stop>
                  <el-switch v-model="tableStyleObj.bottomBorderShow" />
                  {{ $t('crm.product.da4cc4b7d28829b62d02c105fc3110c4') }}
                </span>
              </el-dropdown-item>
              <el-dropdown-item>
                <span @click.stop>
                  <el-switch v-model="tableStyleObj.stripe" />
                  {{ $t('crm.product.a160dfb67e294bbc19cdd6a2963a2b19') }}
                </span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-pagination
            :current-page="currentPage"
            :page-sizes="pageSizes"
            :page-size.sync="pageSize"
            :total="total"
            :pager-count="5"
            class="p-bar"
            layout="prev, pager, next, sizes, total, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </div>
      </template>
    </div>
    <product-detail
      v-if="showDview"
      :id.sync="rowID"
      :page-list="crmType == rowType ? list : []"
      :page-index.sync="rowIndex"
      class="d-view"
      @handle="handleHandle"
      @hide-view="showDview=false" />

    <!-- 新建 -->
    <product-create
      v-if="createShow"
      @close="createShow = false"
      @save-success="handleHandle" />

    <!-- 转移 -->
    <transfer-handle
      v-if="transferDialogShow"
      :props="transferHandleProps"
      :dialog-visible.sync="transferDialogShow"
      @handle="handleHandle" />
  </div>
</template>

<script>
import {
  crmProductTransferAPI,
  crmProductStatusAPI,
  crmProductExcelExportAPI,
  crmProductDeleteAPI
} from '@/api/crm/product'

import ImgView from './components/ImgView'
import ProductCreate from './Create'
import ProductDetail from './Detail'
import TransferHandle from '@/components/Page/SelectionHandle/TransferHandle' // 转移

import TableMixin from '../mixins/Table'

export default {
  /** 客户管理 的 产品列表 */
  name: 'ProductIndex',
  components: {
    ImgView,
    ProductCreate,
    ProductDetail,
    TransferHandle
  },
  mixins: [TableMixin],
  data() {
    return {
      crmType: 'product',
      createShow: false,
      // 转移
      transferDialogShow: false,
      transferHandleProps: {}
    }
  },
  computed: {
    // 可操作选项
    handleOperations() {
      return this.getOperations([
        'transfer',
        'export',
        'delete',
        'start',
        'disable'
      ])
    }
  },
  mounted() {},
  methods: {
    /**
     * @description: 表头事件
     * @param {*} type
     * @return {*}
     */
    tableOperationsClick(type) {
      if (type === 'transfer') {
        this.transferHandleProps = {
        // 场景编辑请求
          request: crmProductTransferAPI,
          params: { ids: this.selectionList.map(item => item[this.crmType + 'Id']) },
          // 帮助提示
          help: this.getHelpObj(this.crmType, 'transfer')
        }
        this.transferDialogShow = true
      } else if (type === 'export') {
        // 成交状态
        this.$wkExport.export(this.crmType, {
          ...this.getExportFieldRequestData(),
          params: { ids: this.selectionList.map(item => item[`${this.crmType}Id`]) },
          request: crmProductExcelExportAPI
        })
      } else if (type === 'delete') {
        this.$confirm(
          this.$t('crm.product.285290fd11dda0901b90f6fa08a17858', { 1: this.selectionList.length }),
          this.$t('crm.product.7d3c2f88bc33234cff490f6599544dd4'),
          {
            confirmButtonText: this.$t('crm.product.fa5149e0db8fd3e338d1597e6a8707f9'),
            cancelButtonText: this.$t('crm.product.13fe40afd23d74fd524d6618cfd92b2a'),
            type: 'warning'
          }
        )
          .then(() => {
            this.loading = true
            crmProductDeleteAPI(this.selectionList.map(item => item[`${this.crmType}Id`]))
              .then(res => {
                this.loading = false
                this.$message({
                  type: 'success',
                  message: this.$t('crm.product.8c8b78cfbbaa924c999b603e7eb7654d')
                })
                this.handleHandle({ type })
              })
              .catch(() => {
                // 批量沟通 可能部分删除成功，需要刷新列表
                this.handleHandle({ type })
                this.loading = false
              })
          })
          .catch(() => {})
      } else if (type === 'start' || type === 'disable') {
        const message = {
          start: this.$t('crm.product.d92ab1c41de169d52503090d72854347'),
          disable: this.$t('crm.product.85dcb2739aad7cdb3a97b4c8103204a4')
        }[type]
        this.$confirm(message, this.$t('crm.product.d241d9e4dda6d9a886c20675fd726935'), {
          confirmButtonText: this.$t('crm.product.857ed93f26b02672e1bffdb87dd62966'),
          cancelButtonText: this.$t('crm.product.0bd8e58c507f9877452486779c9ed4b3'),
          type: 'warning'
        })
          .then(() => {
            this.loading = true
            crmProductStatusAPI({
              ids: this.selectionList.map(item => item.productId),
              status: type === 'start' ? '1' : '0'
            })
              .then(res => {
                this.loading = false
                this.$message({
                  type: 'success',
                  message: this.$t('crm.product.a444ec2af715c6f68fba1d4ff86744ea')
                })
                this.handleHandle({ type })
              })
              .catch(() => {
                this.loading = false
              })
          })
          .catch(() => {})
      }
    },

    /**
     * 通过回调控制class
     */
    cellClassName({ row, column, rowIndex, columnIndex }) {
      if (column.property === 'name') {
        return 'can-visit--underline'
      } else {
        return ''
      }
    },

    /**
     * 新建点击
     */
    createClick() {
      this.createShow = true
    },

    /**
     * 获取状态图标
     */
    getStatusIcon(value) {
      if (value === this.$t('crm.product.8f1122646bd9e3ed59eab5068954fa66')) {
        return {
          icon: 'wk wk-icon-s-up-line',
          style: {
            color: '#00875A',
            marginRight: '4px'
          }
        }
      } else if (value === this.$t('crm.product.6197a954c90187b574cb6541db1ff074')) {
        return {
          icon: 'wk wk-icon-s-down-line',
          style: {
            color: '#DE350B',
            marginRight: '4px'
          }
        }
      }

      return null
    },

    /**
     * @description: 校准产品状态的formType
     * @param {*}
     * @return {*}
     */
    conditionTypeFun(data) {
      if (data && data.fieldName === 'status') {
        return data.fieldName
      }
      return data.formType
    }
  }
}
</script>

<style lang="scss" scoped>
@import "../styles/table.scss";
</style>
